package com.kyivmohyla.kma2.server;

import com.kyivmohyla.kma2.ImportOrder;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.text.SimpleDateFormat;

public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletFileUpload upload = new ServletFileUpload();
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(ImportOrder.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

            FileItemIterator iter = upload.getItemIterator(req);

            FileItemStream item = iter.next();

            InputStream stream = item.openStream();
            ImportOrder order = (ImportOrder) jaxbUnmarshaller.unmarshal(stream);
            JSONObject object = new JSONObject();
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
            object.put("customerName", order.getCustomerName());
            object.put("customerPhone", order.getCustomerPhone());
            object.put("customerAddress", order.getCustomerAddress());
            object.put("customerEmail", order.getCustomerEmail());
            object.put("desirableStart", dateFormat.format(order.getDesirableStart()));
            object.put("desirableEnd", dateFormat.format(order.getDesirableEnd()));
            object.put("commentary", order.getCommentary());
            resp.setContentType("text/html");
            Writer writer = resp.getWriter();
            writer.write(object.toString());
            writer.flush();
            writer.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
